package cn.xiaoyu.su.component;

import cn.xiaoyu.su.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author sufs
 * @date 2022/10/27 14:39
 */
@Component
@Slf4j
public class SmsComponent {

    private static final  String URL_TEMPLATE = "http://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    /**
     * 发送短信验证码
     * @param to
     * @param templateId
     * @param value
     */
    @Async("threadPoolTaskExecutor")
    public void sendCode(String to, String templateId, String value) {
        String url = String.format(URL_TEMPLATE,to,templateId,value);

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization","APPCODE "+smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity(headers);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        log.info("url={},body={}",url,response.getBody());

        if (response.getStatusCode() == HttpStatus.OK) {
            log.info("发送短信验证码成功");
        } else {
            log.error("发送短信验证码失败：{}",response.getBody());
        }

    }
}
